package com.example.administrator.orchardeveryday.fragments;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.alibaba.fastjson.JSONObject;
import com.example.administrator.orchardeveryday.R;
import com.example.administrator.orchardeveryday.adapter.AdvPagerAdapter;
import com.example.administrator.orchardeveryday.adapter.HomeFragmentListAdapter;
import com.example.administrator.orchardeveryday.bean.HomeEntity;
import com.example.administrator.orchardeveryday.config.UrlConstants;
import com.example.administrator.orchardeveryday.ui.FreshActivity;
import com.example.administrator.orchardeveryday.utils.ImageLoaderHelper;
import com.example.administrator.orchardeveryday.widget.GridViewForScrollView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cz.msebera.android.httpclient.Header;
/**
 * A simple {@link Fragment} subclass.
 */
public class HomeFragment extends Fragment implements AdapterView.OnItemClickListener{
    DisplayImageOptions displayImage;
    private AsyncHttpClient httpClient = new AsyncHttpClient();
    private ViewPager vp;
    private LinearLayout dotsLl;
    private ArrayList<ImageView> dots=new ArrayList<>();
    private GridViewForScrollView gv;
    private ListView lv;
    private ArrayList<ImageView> advLists = new ArrayList<>();
    private ArrayList<HomeEntity.BannerEntity> lists = new ArrayList<>();
    private AdvPagerAdapter advAdapter;
    private HomeFragmentListAdapter listAdapter;
    private HomeEntity homeEntity;
    private List<HomeEntity.RotationEntity> rotations;
    private int[] images = {R.mipmap.icon_juice, R.mipmap.icon_flash, R.mipmap.icon_shake,
            R.mipmap.icon_topup, R.mipmap.home_order, R.mipmap.redemption,
            R.mipmap.enterprise, R.mipmap.icon_eattry,};
    private String[] name = {"天天到家", "抢鲜啦", "摇一摇", "充值有礼", "物流售后", "提货券", "企业团购", "免费试吃"};
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            vp.setCurrentItem(msg.what);
        }
    };
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        displayImage = ImageLoaderHelper.getDisplayImageLoader();
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        init(view);
        addHead(inflater);
        loadData();
        return view;
    }
    private void init(View view) {
        lv = (ListView) view.findViewById(R.id.fragment_home_lv);
        listAdapter = new HomeFragmentListAdapter(lists, getActivity());
        lv.setAdapter(listAdapter);
        lv.setOnItemClickListener(this);
    }
    private void addHead(LayoutInflater inflater) {
        View headView = inflater.inflate(R.layout.fragment_home_header, null);
        vp = (ViewPager) headView.findViewById(R.id.fragment_home_vp);
        dotsLl= (LinearLayout) headView.findViewById(R.id.fragment_home_dots_ll);
        gv = (GridViewForScrollView) headView.findViewById(R.id.fragment_home_gridview);
        advAdapter = new AdvPagerAdapter(advLists);
        vp.setAdapter(advAdapter);
        SimpleAdapter gridAdapter = new SimpleAdapter(getActivity(), initGridData(),
                R.layout.item_home_fragment_gridview, new String[]{"img", "name"},
                new int[]{R.id.item_home_fragment_content_img, R.id.item_home_fragment_content_tv});
        gv.setAdapter(gridAdapter);
        gv.setOnItemClickListener(this);
        lv.addHeaderView(headView);
    }

    private List initGridData() {
        ArrayList<HashMap<String, Object>> gridList = new ArrayList<>();
        for (int i = 0; i < images.length; i++) {
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("img", images[i]);
            map.put("name", name[i]);
            gridList.add(map);
        }
        return gridList;
    }
    private void loadData()
    {
        httpClient.post(UrlConstants.URL_HOME, getRequestParams(), new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {

            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                homeEntity=JSONObject.parseObject(responseString,HomeEntity.class);
                if(homeEntity!=null)
                {
                    List<HomeEntity.BannerEntity> banners=homeEntity.getBanner();
                    lists.addAll(banners);
                    listAdapter.notifyDataSetChanged();
                    rotations=homeEntity.getRotation();
                    for (int i = 0; i< rotations.size(); i++) {
                        HomeEntity.RotationEntity rotation=  rotations.get(i);
                        String photo=rotation.getPhoto();
                        ImageView iv = new ImageView(getActivity());
                        iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
                        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                        iv.setLayoutParams(layoutParams);
                        ImageLoader.getInstance().displayImage(photo, iv, displayImage);
                        advLists.add(iv);
                    }
                    advAdapter.notifyDataSetChanged();
                    for (int l = 0; l<rotations.size() ; l++) {
                        ImageView iv=new ImageView(getActivity());
                        ViewGroup.LayoutParams params=new ViewGroup.LayoutParams(50,50);
                        iv.setLayoutParams(params);
                        if(l==0)
                        {
                            iv.setImageResource(R.mipmap.dot);
                        }
                        else
                        {
                            iv.setImageResource(R.mipmap.dot_1);
                        }
                        dots.add(iv);
                        dotsLl.addView(iv);
                    }
                    vp.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                        @Override
                        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                            for (int i = 0; i < dots.size(); i++) {
                                dots.get(i).setImageResource(R.mipmap.dot_1);
                            }
                            dots.get(position).setImageResource(R.mipmap.dot);
                        }

                        @Override
                        public void onPageSelected(int position) {

                        }

                        @Override
                        public void onPageScrollStateChanged(int state) {

                        }
                    });
                    new Thread(){
                        public void run(){
                            boolean flag=true;
                            int index=0;
                            while(true){
                                Message msg=Message.obtain();
                                if(index==advLists.size()){
                                    flag=false;
                                }  else if(index==0)
                                {
                                    flag=true;
                                }
                                if(flag)
                                {
                                    index++;
                                } else
                                {
                                    index--;
                                }
                                msg.what=1;
                                msg.arg1=index;
                                handler.sendEmptyMessageDelayed(index,1000*3);
                                try {
                                    Thread.sleep(2000);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }.start();
                }

            }
        });


    }


    private RequestParams getRequestParams() {
        RequestParams params = new RequestParams();
        params.add("sign", "a286d46bbaec46a42298e95b185fbf3a");
        params.add("timestamp", "1438873575");
        params.add("platform", "ANDROID");
        params.add("source", "app");
        params.add("connect_id", "");
        params.add("region_id", "143949");
        params.add("service", "marketing.banner");
        params.add("device_id", "93789e8978f2eefdcf52006b4d96ee23");
        params.add("channel", "qq");
        params.add("version", "2.3.0");
        return params;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch (position) {
            case 1:
                Intent intent = new Intent(getActivity(), FreshActivity.class);
                startActivity(intent);
                break;
        }
    }
}